package com.lc.pda.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 *
 * @author NASH.LEE
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    public static String FIELD_CREATE_TIME = "createTime";
    public static String FIELD_UPDATE_TIME = "updateTime";
    public static String FIELD_CREATE_BY = "createBy";
    public static String FIELD_UPDATE_BY = "updateBy";

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = getUsername(metaObject);
        if (StringUtils.isNotEmpty(username)) {
            this.setFieldValByName(FIELD_CREATE_TIME, new Date(), metaObject);
            this.setFieldValByName(FIELD_CREATE_BY, username, metaObject);
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_BY, username, metaObject);
        }
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String username = getUsername(metaObject);
        if (StringUtils.isNotEmpty(username)) {
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_BY, username, metaObject);
        }
    }

    protected String getUsername(MetaObject metaObject) {
        if (metaObject.hasGetter(FIELD_CREATE_TIME) && metaObject.hasGetter(FIELD_CREATE_BY) && metaObject.hasGetter(FIELD_UPDATE_TIME)) {
            metaObject.hasGetter(FIELD_UPDATE_BY);
        }
        return null;
    }

}
